package cn.fl.capital.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapRepaymentCondition;
import cn.fl.capital.service.ICapRepaymentService;
import cn.fl.capital.vo.CapRepaymentVO;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.transform.FriBaseInfoVOTransform;
import cn.fl.ref.fribaseinfo.utils.FundRasInsNmChangeUtil;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.risknew.service.IRiskOverdueService;
import com.alibaba.fastjson.JSONObject;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.fribaseinfo.constant.FriBaseInfoConstant;
import fl.ref.fribaseinfo.dto.FriBaseInfoDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 资方账单还款查询 控制层
 */
@Controller
@RequestMapping("/capital/capRepayment")
public class CapRepaymentController {
    private static final Logger logger = LoggerFactory.getLogger(CapRepaymentController.class);

    /**
     *
     */
    @Autowired
    private ICapRepaymentService  capRepaymentService;
    @Autowired
    private ICstBscInfoService cstBscInfoService;

    @Autowired
    private IFriBaseInfoService friBaseInfoService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private IRiskOverdueService overdueService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载toListPage列表页面.", CurrentThreadContext.getCurrentUserName());
        //业务线字典List
        List<KeyValueVO> bussinessLineDicList = sysDictionaryApiService.getKvList("REF0048","11000","0000");

        Pager page = new Pager();
        page.setCurrentPage(1);
        page.setEveryPage(Integer.MAX_VALUE);
        FriBaseInfoQueryCondition qc = new FriBaseInfoQueryCondition();
        qc.setInsSts(FriBaseInfoConstant.FRI_BASE_INFO_INS_STS_PASS);
        qc.setInsUseCd("2");
        qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
        qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        page.setCondition(qc);
        Pager pager = this.friBaseInfoService.searchListPage(page);
        List<FriBaseInfoVO> list = FriBaseInfoVOTransform.toVOList((List<FriBaseInfoDTO>) pager.getResultList());
        //根据金融机构业务线,设置金融机构名称展示字段值
        FundRasInsNmChangeUtil.insNmShowAddBussinessLineDic(list,bussinessLineDicList);
        ModelAndView mav = new ModelAndView("capital/capRepayment/capRepaymentList");
        mav.addObject("friBaseList", list);
        return mav;
    }


    /**
     * 初始化列表
     */
    @RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object initCapRepaymentList(HttpServletRequest request, HttpServletResponse response) {

        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        CapRepaymentCondition qc =new CapRepaymentCondition();
        //支付表号
        String paySchNo = request.getParameter("paySchNo");
        //客户名称
        String cstNm = request.getParameter("cstNm");
        //第三方机构
        String foundInsCode =  request.getParameter("foundInsCode");
        //应收时间
        String receivableTtlStartDate=request.getParameter("receivableTtlStartDate");
        String receivableTtlEndDate=request.getParameter("receivableTtlEndeDate");
        //实收时间
        String receivedTtlStartDate=request.getParameter("receivedTtlStartDate");
        String receivedTtlEndDate=request.getParameter("receivedTtlEndDate");
        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setCstNm(cstNm.trim());
        }
        if (StringUtils.isNotEmpty(paySchNo)) {
            qc.setPaySchNo(paySchNo.trim());
        }
        if (StringUtils.isNotEmpty(foundInsCode)) {
            qc.setFoundInsCode(foundInsCode);
        }
        if (StringUtils.isNotEmpty(receivableTtlStartDate)) {
            qc.setReceivableTtlStartDate(DateUtils.formatStringToDate(receivableTtlStartDate,DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(receivableTtlEndDate)) {
            qc.setReceivableTtlEndeDate(DateUtils.formatStringToDate(receivableTtlEndDate,DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(receivedTtlStartDate)) {
            qc.setReceivedTtlStartDate(DateUtils.formatStringToDate(receivedTtlStartDate,DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(receivedTtlEndDate)) {
            qc.setReceivedTtlEndDate(DateUtils.formatStringToDate(receivedTtlEndDate,DateUtils.YYYY_MM_DD));
        }
        page.setCondition(qc);
        BaseLogUtils.info(logger, "initCapRepaymentList", "初始化CapRepayment列表页面数据.DATA:"+ JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        page= this.capRepaymentService.searchListPage(page);
        List<CapRepaymentVO> list = (List<CapRepaymentVO>) page.getResultList();

        //资管机构名称后添加业务线字典
        if (CollectionUtils.isNotEmpty(list)) {
            //业务线字典List
            List<KeyValueVO> bussinessLineDicList = sysDictionaryApiService.getKvList("REF0048","11000","0000");
            //查询第三方机构
            List<FriBaseInfoVO> friBaseInfoVOList = this.overdueService.getFriBaseInfoList();
            //根据金融机构业务线,设置金融机构名称展示字段值
            FundRasInsNmChangeUtil.insNmShowAddBussinessLineDic(friBaseInfoVOList,bussinessLineDicList);
            if (CollectionUtils.isNotEmpty(friBaseInfoVOList)) {
                for (CapRepaymentVO capRepaymentVOTemp : list) {
                    if (StringUtils.isEmpty(capRepaymentVOTemp.getFoundInsCode())) {
                        continue;
                    }
                    for (FriBaseInfoVO friBaseInfoVOTemp : friBaseInfoVOList) {
                        if (StringUtils.isNotEmpty(friBaseInfoVOTemp.getId()) && StringUtils.isNotEmpty(friBaseInfoVOTemp.getFundRasInsNmShow())
                                && capRepaymentVOTemp.getFoundInsCode().equals(friBaseInfoVOTemp.getInsCode())) {
                            capRepaymentVOTemp.setFoundInsName(friBaseInfoVOTemp.getFundRasInsNmShow());
                            break;
                        }
                    }
                }
            }
        }

        ListPageVO<CapRepaymentVO> listPage = new ListPageVO<CapRepaymentVO>(list, page.getTotalCount());
        return listPage;
    }


    /**
     * 初始化列表
     *      应收租金合计：receivableTtlAmtSum
     *      实收租金合计：receivedTtlAmtSum
     *      实收罚息合计：penaltySum
     */
    @RequestMapping(value = "/getSumAmt.do", method = { RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> getSumAmt(HttpServletRequest request, HttpServletResponse response) {

        CapRepaymentCondition qc =new CapRepaymentCondition();
        String paySchNo = request.getParameter("paySchNo");//支付表号
        String cstNm = request.getParameter("cstNm");//客户名称
        String foundInsCode =  request.getParameter("foundInsCode");
        String receivableTtlStartDate=request.getParameter("receivableTtlStartDate");
        String receivableTtlEndDate=request.getParameter("receivableTtlEndeDate");
        String receivedTtlStartDate=request.getParameter("receivedTtlStartDate");
        String receivedTtlEndDate=request.getParameter("receivedTtlEndDate");
        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setCstNm(cstNm.trim());
        }
        if (StringUtils.isNotEmpty(paySchNo)) {
            qc.setPaySchNo(paySchNo.trim());
        }
        if (StringUtils.isNotEmpty(foundInsCode)) {
            qc.setFoundInsCode(foundInsCode);
        }
        if (StringUtils.isNotEmpty(receivableTtlStartDate)) {
            qc.setReceivableTtlStartDate(DateUtils.formatStringToDate(receivableTtlStartDate,DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(receivableTtlEndDate)) {
            qc.setReceivableTtlEndeDate(DateUtils.formatStringToDate(receivableTtlEndDate,DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(receivedTtlStartDate)) {
            qc.setReceivedTtlStartDate(DateUtils.formatStringToDate(receivedTtlStartDate,DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotEmpty(receivedTtlEndDate)) {
            qc.setReceivedTtlEndDate(DateUtils.formatStringToDate(receivedTtlEndDate,DateUtils.YYYY_MM_DD));
        }
        BaseLogUtils.info(logger, "getSumAmt", "getSumAmt页面数据.DATA:"+ JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName());
        return  this.capRepaymentService.selectCapRepaymentSum(qc);
    }


    @RequestMapping(value = "/toPrjPrdPayDetailPage.do", method = { RequestMethod.GET})
    public ModelAndView toPrjPrdPayDetailPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载toPrjPrdPayDetailPage列表页面.", CurrentThreadContext.getCurrentUserName());
        String paySchId = request.getParameter("paySchId");
        ModelAndView mav = new ModelAndView("capital/capRepayment/capPayDetailList");
        mav.addObject("paySchId", paySchId);
        return mav;
    }

    @RequestMapping(value = "/initDetailList.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object initDetailList(HttpServletRequest request, HttpServletResponse response) {

        String paySchId = request.getParameter("paySchId");
        if(StringUtils.isEmpty(paySchId)){
            BaseLogUtils.error(logger, "initDetailList",  "paySchId不能为空", CurrentThreadContext.getCurrentUserName());
            return null;
        }
        CapRepaymentCondition capRepaymentCodition=new  CapRepaymentCondition();
        List<Long> paySchIdList=new ArrayList<Long>();
        paySchIdList.add(Long.parseLong(paySchId));
        capRepaymentCodition.setPaySchIdList(paySchIdList);
        return capRepaymentService.selectPaySchDList(capRepaymentCodition);
    }
}
